
from PIL import Image
import PIL.ImageDraw as ImageDraw
import PIL.ImageFont as ImageFont


jpgname = './00066.jpg'
txtname = './00066.txt'
outputname = './66.jpg'
img = Image.open(jpgname)  # 打开图片1.jpg
a = ImageDraw.ImageDraw(img)  # 用a来表示右侧这段
# <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=800x600 at 0x1B2DEA98748>
print(img)
print(img.size)
width = img.size[0]
height = img.size[1]
#print(width, height, sep="  ")

classes = {0: "face", 2: "mask"}
# 读txt
f = open(txtname, "r")
text = f.readlines()

index = 0
for row in text:
    index += 1
    l = row.split(" ")
    classes_key = int(l[0])
    x = float(l[1])
    y = float(l[2])
    w = float(l[3])
    h = float(l[4])

    #print(classes[classes_key], x, y, w, h, sep="  ")

    rec_class = classes[classes_key]
    rec_w = int(w * width)
    rec_h = int(h * height)
    rec_x1 = int(x * width - rec_w / 2)
    rec_y1 = int(y * height - rec_h / 2)
    rec_x2 = int(x * width + rec_w / 2)
    rec_y2 = int(y * height + rec_h / 2)
    #print(rec_x1, rec_y1, rec_x2, rec_y2)

    # 设置字体（LiberationSans-Regular.ttf这是我ubuntu16.04自带的字体)
    font = ImageFont.truetype('C:\\Windows\\Fonts\\msyh.ttc', 15)

    # 打开图片
    # imageFile = "2.jpg"
    # im1=Image.open(imageFile)

    # 在图片上添加文字 1
    draw = ImageDraw.Draw(img)

    if classes_key == 0:
        if rec_y1 - 10 < 0:
            draw.text((rec_x1, rec_y1 + rec_h), rec_class + str(index), (255, 0, 0), font=font)
            draw = ImageDraw.Draw(img)
            # 在100，150起点画长800宽200的图形，填充白色，边框黑色，边框像素为1
            a.rectangle(((rec_x1, rec_y1), (rec_x2, rec_y2)), outline='red', width=4)
        else:
            # (0,0):坐标 "XUNALOVE"：添加的字体 (0,0,255):字体颜色 font:字体大小
            draw.text((rec_x1, rec_y1 - 20), rec_class + str(index), (255, 0, 0), font=font)
            draw = ImageDraw.Draw(img)
            # 在100，150起点画长800宽200的图形，填充白色，边框黑色，边框像素为1
            a.rectangle(((rec_x1, rec_y1), (rec_x2, rec_y2)), outline='red', width=4)



    else:
        if rec_y1 - 10 < 0:
            # (0,0):坐标 "XUNALOVE"：添加的字体 (0,0,255):字体颜色 font:字体大小
            draw.text((rec_x1, rec_y1 + rec_h), rec_class + str(index), (0, 255, 0), font=font)
            draw = ImageDraw.Draw(img)
            # 在100，150起点画长800宽200的图形，填充白色，边框黑色，边框像素为1
            a.rectangle(((rec_x1, rec_y1), (rec_x2, rec_y2)), outline='green', width=4)
        else:
            # (0,0):坐标 "XUNALOVE"：添加的字体 (0,0,255):字体颜色 font:字体大小
            draw.text((rec_x1, rec_y1 - 20), rec_class + str(index), (0, 255, 0), font=font)
            draw = ImageDraw.Draw(img)
            # 在100，150起点画长800宽200的图形，填充白色，边框黑色，边框像素为1
            a.rectangle(((rec_x1, rec_y1), (rec_x2, rec_y2)), outline='green', width=4)

    # 保存
    img.save(outputname)
